package com.newsanalysis.analysis;

import com.newsanalysis.model.entity.News;
import com.newsanalysis.service.NewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class NewsAnalysisService {
    private final NewsService newsService;
    private final TextAnalyzer textAnalyzer;
    
    // 对单条新闻进行分析
    public News analyzeNews(News news) {
        if (news == null) {
            return null;
        }
        
        // 情感分析
        String sentiment = textAnalyzer.analyzeSentiment(news.getTitle() + " " + news.getContent());
        news.setSentiment(sentiment);
        
        // 新闻分类
        String category = textAnalyzer.classifyNews(news.getTitle(), news.getContent());
        news.setCategory(category);
        
        // 热度计算（假设有浏览量数据，这里简单设置为0）
        int hotIndex = textAnalyzer.calculateHotIndex(news.getTitle(), news.getContent(), 0);
        news.setHotIndex(hotIndex);
        
        // 更新新闻数据
        newsService.updateNews(news);
        
        return news;
    }
    
    // 批量分析新闻
    public void batchAnalyzeNews(List<News> newsList) {
        newsList.forEach(this::analyzeNews);
    }
    
    // 提取新闻关键词
    public List<Map.Entry<String, Integer>> extractNewsKeywords(Long newsId, int limit) {
        Optional<News> newsOpt = newsService.findById(newsId);
        if (newsOpt.isEmpty()) {
            return null;
        }
        
        News news = newsOpt.get();
        return textAnalyzer.extractKeywords(news.getTitle() + " " + news.getContent(), limit);
    }
    
    // 分析新闻类别分布
    public Map<String, Long> analyzeCategoryDistribution() {
        return newsService.getCategoryDistribution();
    }
    
    // 分析情感倾向分布
    public Map<String, Long> analyzeSentimentDistribution() {
        return newsService.getSentimentDistribution();
    }
}

